import { fileURLToPath, pathToFileURL } from 'url';
import fs from 'fs';


export const findAllControllerFiles = function(){
    let baseControllerUrl = new URL('../controller', import.meta.url).href;
    let baseControllerPath = fileURLToPath(baseControllerUrl);
    let allFiles = fs.readdirSync(baseControllerPath);
    let allControllerFiles = allFiles.filter(item => item.endsWith('.js'))
        .map(item => pathToFileURL(`${baseControllerPath}/${item}`).href);
     return allControllerFiles;
}
export const registryRoute = function (router, controllerFiles) {
    controllerFiles.forEach(async file => {
        
        let { default: obj } = await import(file)
        for (var item in obj) {
            let keyArr = item.split(' ');
            let reqMethod = keyArr[0];
            let reqPath = keyArr[1];
            let reqFn = obj[item];
            if (reqMethod === 'get') {
                router.get(reqPath, reqFn);
            }
            if (reqMethod === 'post') {
                router.post(reqPath, reqFn);
            }
            if (reqMethod === 'put') {
                router.put(reqPath, reqFn);
            }
            if (reqMethod === 'delete') {
                router.delete(reqPath, reqFn);
            }
        }
    })
}